package com.atguigu.cloud.service.impl;

import com.atguigu.cloud.entity.LovColumnConfig;
import com.atguigu.cloud.entity.LovConfig;
import com.atguigu.cloud.mapper.LovConfigMapper;
import com.atguigu.cloud.service.LovColumnConfigService;
import com.atguigu.cloud.service.LovConfigService;
import com.atguigu.cloud.utils.DynamicSqlParser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Lov配置服务实现类
 * 
 * @author atguigu
 * @since 2024-01-01
 */
@Service
public class LovConfigServiceImpl extends ServiceImpl<LovConfigMapper, LovConfig> implements LovConfigService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private LovColumnConfigService lovColumnConfigService;

    @Autowired
    private DynamicSqlParser dynamicSqlParser;

    @Override
    public LovConfig selectById(Long id) {
        LovConfig lovConfig = super.getById(id);
        if (lovConfig != null) {
            // 加载列配置
            List<LovColumnConfig> columns = lovColumnConfigService.getByLovConfigId(lovConfig.getId());
            lovConfig.setColumns(columns);
        }
        return lovConfig;
    }

    @Override
    public List<LovConfig> list() {
        List<LovConfig> lovConfigs = super.list();
        if (lovConfigs != null && !lovConfigs.isEmpty()) {
            // 为每个配置加载列配置
            for (LovConfig lovConfig : lovConfigs) {
                List<LovColumnConfig> columns = lovColumnConfigService.getByLovConfigId(lovConfig.getId());
                lovConfig.setColumns(columns);
            }
        }
        return lovConfigs;
    }

    @Override
    public LovConfig selectByLovCode(String lovCode) {
        LambdaQueryWrapper<LovConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LovConfig::getLovCode, lovCode)
                .eq(LovConfig::getEnabled, true);
        LovConfig lovConfig = this.getOne(wrapper);

        if (lovConfig != null) {
            // 加载列配置
            List<LovColumnConfig> columns = lovColumnConfigService.getByLovConfigId(lovConfig.getId());
            lovConfig.setColumns(columns);
        }

        return lovConfig;
    }

    @Override
    public Map<String, Object> getLovDataWithPage(String lovCode, Map<String, Object> queryParams, Integer pageNum,
            Integer pageSize) {
        LovConfig lovConfig = selectByLovCode(lovCode);
        if (lovConfig == null) {
            throw new RuntimeException("Lov配置不存在或已禁用: " + lovCode);
        }

        String sqlTemplate = lovConfig.getDataSourceSql();

        // 构建查询参数（支持MyBatis动态SQL）
        Map<String, Object> params = new HashMap<>();
        if (queryParams != null && !queryParams.isEmpty()) {
            // 将查询参数添加到params中，供MyBatis动态SQL使用
            params.putAll(queryParams);
        }

        // 使用DynamicSqlParser解析动态SQL（支持<if>、<where>等MyBatis标签）
        DynamicSqlParser.ParsedSql parsedSql = dynamicSqlParser.parseSql(sqlTemplate, params);
        String sql = parsedSql.getSql();
        Object[] paramArray = parsedSql.getParameterArray();

        // 查询总数
        String countSql = "SELECT COUNT(*) FROM (" + sql + ") AS t";
        Integer total = jdbcTemplate.queryForObject(countSql, Integer.class, paramArray);

        // 分页参数处理
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = lovConfig.getPageSize() != null ? lovConfig.getPageSize() : 10;
        }

        // 添加分页
        int offset = (pageNum - 1) * pageSize;
        String pageSql = sql + " LIMIT " + pageSize + " OFFSET " + offset;

        // 执行分页查询
        List<Map<String, Object>> list = jdbcTemplate.queryForList(pageSql, paramArray);

        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("total", total);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("pages", (int) Math.ceil((double) total / pageSize));

        return result;
    }

    @Override
    public List<Map<String, Object>> getLovData(String lovCode, String keyword) {
        LovConfig lovConfig = selectByLovCode(lovCode);
        if (lovConfig == null) {
            throw new RuntimeException("Lov配置不存在或已禁用: " + lovCode);
        }

        String sqlTemplate = lovConfig.getDataSourceSql();

        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        if (keyword != null && !keyword.trim().isEmpty()) {
            params.put("keyword", keyword);
            params.put("displayField", lovConfig.getDisplayField());
        }

        // 使用DynamicSqlParser解析动态SQL
        DynamicSqlParser.ParsedSql parsedSql = dynamicSqlParser.parseSql(sqlTemplate, params);
        String sql = parsedSql.getSql();
        Object[] paramArray = parsedSql.getParameterArray();

        return jdbcTemplate.queryForList(sql, paramArray);
    }

    @Override
    public String getDisplayText(String lovCode, String value) {
        LovConfig lovConfig = selectByLovCode(lovCode);
        if (lovConfig == null) {
            return value;
        }

        String sqlTemplate = lovConfig.getDataSourceSql();
        String displayField = lovConfig.getDisplayField();
        String valueField = lovConfig.getValueField();

        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put(valueField, value);

        // 使用DynamicSqlParser解析动态SQL
        DynamicSqlParser.ParsedSql parsedSql = dynamicSqlParser.parseSql(sqlTemplate, params);
        String sql = parsedSql.getSql();
        Object[] paramArray = parsedSql.getParameterArray();

        List<Map<String, Object>> result = jdbcTemplate.queryForList(sql, paramArray);
        if (!result.isEmpty()) {
            return String.valueOf(result.get(0).get(displayField));
        }

        return value;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveLovConfigWithColumns(LovConfig lovConfig) {
        // 保存LOV配置
        boolean success = this.save(lovConfig);

        // 保存列配置
        if (success && lovConfig.getColumns() != null && !lovConfig.getColumns().isEmpty()) {
            lovColumnConfigService.saveColumns(lovConfig.getId(), lovConfig.getColumns());
        }

        return success;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateLovConfigWithColumns(LovConfig lovConfig) {
        // 更新LOV配置
        boolean success = this.updateById(lovConfig);

        // 更新列配置
        if (success && lovConfig.getColumns() != null) {
            lovColumnConfigService.saveColumns(lovConfig.getId(), lovConfig.getColumns());
        }

        return success;
    }

    @Override
    public Map<String, Object> queryWithCustomParams(String lovCode, Map<String, Object> customParams,
            Integer pageNum, Integer pageSize) {
        LovConfig lovConfig = selectByLovCode(lovCode);
        if (lovConfig == null) {
            throw new RuntimeException("LOV配置不存在或已禁用: " + lovCode);
        }

        String sqlTemplate = lovConfig.getDataSourceSql();

        // 使用动态SQL解析器解析SQL
        DynamicSqlParser.ParsedSql parsedSql = dynamicSqlParser.parseSql(sqlTemplate, customParams);

        String sql = parsedSql.getSql();
        Object[] params = parsedSql.getParameterArray();

        // 查询总数
        String countSql = "SELECT COUNT(*) FROM (" + sql + ") AS t";
        Integer total = jdbcTemplate.queryForObject(countSql, Integer.class, params);

        // 分页参数处理
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = lovConfig.getPageSize() != null ? lovConfig.getPageSize() : 10;
        }

        // 添加分页
        int offset = (pageNum - 1) * pageSize;
        String pageSql = sql + " LIMIT " + pageSize + " OFFSET " + offset;

        // 执行分页查询
        List<Map<String, Object>> list = jdbcTemplate.queryForList(pageSql, params);

        // 封装结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("total", total);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("pages", (int) Math.ceil((double) total / pageSize));

        return result;
    }
}
